package com.sjgs.gis.common;

import java.lang.reflect.Field;

import com.sjgs.gis.annotation.AutoIncKey;
import com.sjgs.gis.domain.SequenceId;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import javax.annotation.Resource;

/**
 * 保存文档监听类<br>
 * 在保存对象时，通过反射方式为其生成ID
 *
 * @author jxw
 * @date 2020年5月27日
 */
@Component
@ConditionalOnProperty(value = "spring.data.mongodb.enabled",havingValue = "true")
public class SaveEventListener extends AbstractMongoEventListener<Object> {

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * @author jxw
     * @date 2020年5月27日
    */
    @Override
    public void onBeforeConvert(BeforeConvertEvent<Object> event) {
        final Object source = event.getSource();
        if (source != null) {
            ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
                @Override
                public void doWith(Field field) throws IllegalAccessException {
                    //将一个字段设置为可读写，主要针对private字段；
                    ReflectionUtils.makeAccessible(field);
                    // 如果字段添加了我们自定义的AutoValue注解
                    if (field.isAnnotationPresent(AutoIncKey.class)
                            && field.get(source) instanceof Number) {
                        // 设置自增ID
                        if(field.get(source).equals(null)){
                            field.set(source, getNextAutoId(source.getClass().getSimpleName()));
                        }
                    }
                }
            });
        }
    }

    /**
     * 获取下一个自增ID
     *
     * @param collName 集合名
     * @return
     * @author jxw
     */
    public Long getNextAutoId(String collName) {
        Query query = new Query(Criteria.where("collName").is(collName));
        Update update = new Update();
        update.inc("seqId", 1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);
        options.returnNew(true);
        SequenceId seq = mongoTemplate
                .findAndModify(query, update, options, SequenceId.class);
        return seq.getSeqId();
    }
}
